package logic

import (
	"context"
	"fmt"
	"user_srv/models"

	"user_srv/internal/svc"
	"user_srv/user_srv"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *user_srv.LoginRequest) (*user_srv.LoginResponse, error) {
	// todo: add your logic here and delete this line
	var user models.User
	get, _ := models.RDB.Get(models.Ctx, in.Phone).Result()
	if get != in.Code {
		return nil, fmt.Errorf("验证码错误")
	}
GetUser:
	if models.DB.Where("phone = ?", in.Phone).Limit(1).Find(&user).Error != nil {
		return nil, fmt.Errorf("服务器繁忙")
	}
	if user.ID == 0 {
		if models.DB.Create(&models.User{
			Phone:    in.Phone,
			UserName: in.Phone + "用户",
			ValiOver: 0,
		}).Error != nil {
			return nil, fmt.Errorf("服务器繁忙")
		}
		goto GetUser
	}
	return &user_srv.LoginResponse{
		UserId:   int64(user.ID),
		ValiOver: int64(user.ValiOver),
	}, nil
}
